package com.miaopasi.securitydemo.config.security.handler;

import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败
 *
 * @author lixin
 */
@Component
public class JsonFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(
            HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception
    ) throws IOException, ServletException {
        Console.log("登录失败，{}", exception);
        Dict res = Dict.create().set("code", 1000).set("msg", "登录失败");
        if (exception instanceof UsernameNotFoundException) {
            res.set("data", "用户名不存在");
        } else if (exception instanceof LockedException) {
            res.set("data", "账号被锁定");
        } else if (exception instanceof DisabledException) {
            res.set("data", "账号被禁用");
        } else if (exception instanceof CredentialsExpiredException) {
            res.set("data", "密码过期");
        } else if (exception instanceof AccountExpiredException) {
            res.set("data", "账号过期");
        } else if (exception instanceof BadCredentialsException) {
            res.set("data", "账号密码输入有误");
        } else {
            res.set("data", "登录失败（" + exception.getMessage() + "）");
        }
        ServletUtil.write(response, JSONUtil.toJsonStr(res), ContentType.JSON.toString(CharsetUtil.CHARSET_UTF_8));
    }
}
